/*
 * Copyright 2008 Karel Klic.
 * This file is part of Oslavanský Bot.
 * 
 * Oslavanský Bot is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package categorybot;

/**
 * Finds the right place to add a new category in the word definition text.
 */
public class CategoryPlaceFinder {
  /**
   * Checks if the text provided contains just interwiki links and white spaces.
   * @param text
   * The word definition text. Wiki syntax.
   * @return
   * True if the text contains just interwiki links and white spaces.
   * False otherwise.
   */
  static public boolean isPlaceBeforeInterWiki(String text) {
    int bracketLevel = 0;
    boolean beforeColon = true;
    for (char c : text.toCharArray()) {
      if (Character.isWhitespace(c))
        continue;
      if (c == '[') {
        bracketLevel++;
        if (bracketLevel == 2) {
          beforeColon = true;
        }
        continue;
      }
      if (c == ']') {
        if (bracketLevel == 2) {
          if (beforeColon)
            return false;
        }
        if (bracketLevel <= 0) {
          return false;
        }
        bracketLevel--;
        continue;
      }
      
      // Other characters.
      if (bracketLevel != 2)
        return false;
      
      if (c == ':') {
        if (!beforeColon) // second ':'
          return false;
        beforeColon = false;
      }
    }
    
    return true;
  }
       
  /**
   * Finds the right place to add a new category in the word definition text.
   * @param text
   * The word definition text. Wiki syntax.
   * @return
   * Offset to the word definition text.
   */
  static public int getOffset(String text) {
    int lastCategoryBeginOffs = text.lastIndexOf("[[Kategorie:");
    if (lastCategoryBeginOffs != -1) {
       int endOfLastCategory = text.indexOf("]]", lastCategoryBeginOffs);
       if (endOfLastCategory != -1)
         return endOfLastCategory + 2;
    }
    
    // No categories presented.
    // Hledame misto co nejvice na zacatku textu, za kterym jsou pouze
    // texty v hranatych zavorkach a mezery.
    int lastHeader = text.lastIndexOf("=");
    if (lastHeader == -1)
      lastHeader = 0;
    
    for (int i = lastHeader; i < text.length(); ++i) {
      if (isPlaceBeforeInterWiki(text.substring(i)))
        return i;
    }
    
    return text.length();
  }
}
